package com.apps.ftapp.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apps.ftapp.R;
import com.apps.ftapp.activity.MyStSucActivity;
import com.apps.ftapp.bean.ExamOption;
import com.apps.ftapp.bean.ExamQuestion;
import com.apps.ftapp.bean.QuestionEntry;
import com.apps.ftapp.db.Singleton;
import com.apps.ftapp.fragment.ExamMaterialFragment;
import com.apps.ftapp.fragment.ExamMultiSelectFragment;
import com.apps.ftapp.fragment.ExamRadioFragment;
import com.apps.ftapp.model.ZhenTiNewModel;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.StatusBarUtils;
import com.apps.ftapp.util.Timer;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaeger.library.StatusBarUtil;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;

public class ExamActivity extends FragmentActivity implements IExamResponseListener, View.OnClickListener {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.txt_timer)
    TextView txtTimer;
    @BindView(R.id.fenxiang)
    ImageView fenxiang;
    @BindView(R.id.shoucang)
    ImageView shoucang;
    @BindView(R.id.timu)
    ImageView timu;
    @BindView(R.id.gengduo)
    RelativeLayout gengduo;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;
    @BindView(R.id.fragment_draw)
    FrameLayout fragmentDraw;
    private long baseTimer;

    private static boolean misScrolled = false;
    private String keys;
    private ZhenTiNewModel zhenTiNewModel = new ZhenTiNewModel();


    final Gson gson = new Gson();
    private String id;

    private String questionID;//当前题目ID

    Singleton singleton = Singleton.getInstance();

    private List<ExamQuestion> mQuestion = new ArrayList<>();


    private int current = 0;

    ViewPagerAdapter mViewPagerAdapter;

    private String lmname;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exam);
        ButterKnife.bind(this);
        // 初始化ShareSDK（不可缺失）
        ShareSDK.initSDK(this);

        StatusBarUtil.setColor(ExamActivity.this, Color.WHITE, 1);
        StatusBarUtils.StatusBarLightMode(this);

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        id = bundle.getString("id");
//        lmname = bundle.getString("lmname");
//        initView();
        L.i("main", "-------------------------------------" + id);
        loadData(id);

        Timer timer = new Timer(txtTimer);
        timer.start(txtTimer);

        imgBack.setOnClickListener(this);
        shoucang.setOnClickListener(this);
        timu.setOnClickListener(this);
        fenxiang.setOnClickListener(this);
//
//        Handler myhandler = new Handler(){
//             public void handleMessage(android.os.Message msg) {
//                                if (0 == ExamActivity.this.baseTimer) {
//                                    ExamActivity.this.baseTimer = SystemClock.elapsedRealtime();
//                                 }
//
//                               int time = (int)((SystemClock.elapsedRealtime() - ExamActivity.this.baseTimer) / 1000);
////                                String hh = new DecimalFormat("00").format(time / 3600);
//                                String mm = new DecimalFormat("00").format(time % 3600 / 60);
//                                String ss = new DecimalFormat("00").format(time % 60);
//                                if (null != ExamActivity.this.txtTimer) {
//                                       txtTimer.setText( mm + ":" + ss);
//                                    }
//                                sendMessageDelayed(Message.obtain(this, 0x0), 1000);
//             }
//         };
//        myhandler.sendMessageDelayed(Message.obtain(myhandler, 0x0), 1000);

    }


    private void initView() {

        singleton.clear();
        collectQuestion(mQuestion.get(current).getCollection() == 1);

        mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mQuestion);
        mViewPager.setAdapter(mViewPagerAdapter);

//        ViewPagerUtils.setSliderTransformDuration(mViewPager, 300, new DecelerateInterpolator());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == mQuestion.size()) {
                    L.i("main", "最后。。。。。。。。。");
                    mViewPagerAdapter.notifyDataSetChanged();
                } else {
                    //更新收藏状态
                    collectQuestion(mQuestion.get(position).getCollection() == 1);
                }
                current = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        misScrolled = false;
                        break;
                    case ViewPager.SCROLL_STATE_SETTLING:
                        misScrolled = true;
                        break;
                    case ViewPager.SCROLL_STATE_IDLE:
                        if (mViewPager.getCurrentItem() == mViewPager.getAdapter().getCount() - 1 && !misScrolled) {
                            L.i("main", "=====继续。。。。。");
                            ActivitySkipUtil.skipAnotherActivity(ExamActivity.this, MyStSucActivity.class, false);

                        }
                        misScrolled = true;
                        break;
                }
            }
        });

//        关掉 右划 返回
//        disableSlideBack();
//
//        Arad.bus.register(this);
    }


    public void collectQuestion(boolean fill) {
        if (fill) {
            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_2));
        } else {
            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_1));
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                showpopup();
                break;
            case R.id.shoucang:

                sc();
                break;

            case R.id.timu:
                ActivitySkipUtil.skipAnotherActivity(ExamActivity.this, MyStSucActivity.class, false);
                break;

            case R.id.fenxiang:

                share();
                break;

        }
    }


    /**
     * 收藏
     */
    private void sc() {
        //判断是否收藏
        //
        L.i("main", mQuestion.get(current).getCollection() + "kljkj>>>>>>" + current + ">>>>" + mQuestion.get(current).getStem());
        if (0 == mQuestion.get(current).getCollection()) {
            L.i("main", "收藏。。。");
            RequestParams params = new RequestParams();
            params.put("token", Constant.token);
            params.put("userId", Constant.uid);
            params.put("question_id", zhenTiNewModel.getItems().get(current).getQuestionId());
            params.put("targetType", "testpaper");
            params.put("targetId", zhenTiNewModel.getItems().get(current).getTestId());
            Async.post("question/favorite", params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    if (statusCode == 200) {
                        L.i("main", new String(responseBody));
                        try {
                            //请求成功
                            Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                            L.i("main", jsonBean.toString());
                            if (1 == Tools.isDoubleNull(jsonBean.get("success")) || 1.0 == Tools.isDoubleNull(jsonBean.get("success"))) {
                                Toasty.normal(getApplicationContext(), "收藏成功").show();
//                            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_2));
//                            result.getData().get(cur).setFavorite("1");
                                mQuestion.get(current).setCollection(1);
                                L.i("main", ">>>" + current);
                                collectQuestion(mQuestion.get(current).getCollection() == 1);
                            } else {
//                            mQuestion.get(cur).setCollection(0);
                                Toasty.normal(getApplicationContext(), Tools.isNull(jsonBean.get("error"))).show();
                            }
                        } catch (Exception e) {
                        }
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                }
            });
        } else {

            //取消收藏

            L.i("main", "取消收藏。。。");
            RequestParams params = new RequestParams();
            params.put("token", Constant.token);
            params.put("userId", Constant.uid);
            params.put("question_id", zhenTiNewModel.getItems().get(current).getQuestionId());
            params.put("targetType", "testpaper");
            params.put("targetId", zhenTiNewModel.getItems().get(current).getTestId());
            Async.post("question/unfavorite", params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    if (statusCode == 200) {
                        L.i("main", new String(responseBody));
                        try {
                            //请求成功
                            Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                            L.i("main", jsonBean.toString());
                            if (1 == Tools.isDoubleNull(jsonBean.get("success")) || 1.0 == Tools.isDoubleNull(jsonBean.get("success"))) {
                                Toasty.normal(getApplicationContext(), "取消收藏").show();
//                            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_2));
//                            result.getData().get(cur).setFavorite("1");
                                mQuestion.get(current).setCollection(0);
                                L.i("main", ">>>" + current);
                                collectQuestion(mQuestion.get(current).getCollection() == 1);
                            } else {
//                            mQuestion.get(cur).setCollection(0);
                                Toasty.normal(getApplicationContext(), Tools.isNull(jsonBean.get("error"))).show();
                            }
                        } catch (Exception e) {
                        }
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                }
            });

        }


    }

    /**
     * Viewpager 内容
     */
    private class ViewPagerAdapter extends FragmentStatePagerAdapter {

        List<ExamQuestion> mQuestionList;

        ViewPagerAdapter(FragmentManager fm, List<ExamQuestion> questionList) {
            super(fm);
            mQuestionList = questionList;
//            L.i("main",".,.,.,.,.,.,.,.,.,.,.,.,.,."+questionList.toString());
        }

        @Override
        public Fragment getItem(int position) {
//            ExamQuestion question;
//            if(1==mQuestionList.size()&&position==1){
//                question = mQuestionList.get(position-1);
//            }else{
//                if (position == mQuestionList.size()) {
//                    //结束
////                return ExamPreviewFragment.newInstance(mTitle, mPresenter.getAnswerRecordJson(), mPresenter.getSeconds(), type);
//                }
//                question = mQuestionList.get(position);
//            }

            ExamQuestion question = mQuestionList.get(position);

//            L.i("main",".,.,.,.,.,.,.,.,.,.,.,.,.,.");

            QuestionEntry entry = new QuestionEntry();
            entry.setExamQuestion(question);
            entry.setPosition(position);
            entry.setTitle(Tools.getType(question.getType()));
            entry.setCount(mQuestionList.size());
            entry.setExam_or_analysis(0);
            entry.setLmname(lmname);


            switch (question.getType()) {
                case 0://单选题
//                    timu.setVisibility(View.VISIBLE);
                    return ExamRadioFragment.newInstance(entry, false);
                case 1://多选题
//                    timu.setVisibility(View.VISIBLE);
                    return ExamMultiSelectFragment.newInstance(entry);
                case 2://不定项选择题
//                    timu.setVisibility(View.VISIBLE);
                    return ExamMultiSelectFragment.newInstance(entry);
                //TODO 3
                case 3://填空题
//                    timu.setVisibility(View.GONE);
                    return ExamMaterialFragment.newInstance(entry);
                case 4://判断题
//                    timu.setVisibility(View.VISIBLE);
                    return ExamRadioFragment.newInstance(entry, false);
                case 5://问题题
//                    timu.setVisibility(View.GONE);
                    return ExamMaterialFragment.newInstance(entry);
                case 6://材料题
//                    timu.setVisibility(View.GONE);
                    return ExamMaterialFragment.newInstance(entry);
                case 7:
                case 8:
                case 9:
                case 10:
                case 11:
                case 12:
                case 13:
                    return ExamMaterialFragment.newInstance(entry);

            }

            return ExamRadioFragment.newInstance(entry, false);
        }

        @Override
        public int getItemPosition(Object object) {
//            if (object instanceof ExamPreviewFragment) {
//                return POSITION_NONE;
//            }
            return super.getItemPosition(object);
        }

        @Override
        public int getCount() {
            return (mQuestionList == null || mQuestionList.size() == 0) ? 0 : mQuestionList.size();
        }
    }


    @Override
    public void onRadio(String selectedId, int whichOne) {
        L.i(selectedId + ":我是第" + whichOne + "个题");

        //


        ExamQuestion question = mQuestion.get(whichOne);
        boolean isCorrect = false;
        for (ExamOption option : question.getDataList()) {
            if (option.getIs_correct() == 1) {
                if (option.getId().equals(selectedId)) {
                    isCorrect = true;
                    break;
                }
            }
        }
        Singleton.getInstance().updDatiList(whichOne + 1, true);


        Map m = new HashMap();
        m.put("id", question.getId());
        m.put("ans", selectedId + "");
        m.put("keys", question.getType());
        singleton.addData(m);

//
//        if(1==mQuestion.size()){
//            //结束
//
//            ActivitySkipUtil.skipAnotherActivity(ExamActivity.this,MyStSucActivity.class,false);
//            return;
//
//        }

        if (whichOne == mQuestion.size() - 1) {
            L.i("结束");
            ActivitySkipUtil.skipAnotherActivity(ExamActivity.this, MyStSucActivity.class, false);

        } else {
            gotoNextPage(whichOne);
        }


//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(selectedId);
//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(isCorrect ? 1 : 0);

//        gotoNextPage(whichOne);
    }

    @Override
    public void onMutil(List<String> selectedID, int whichOne) {

        if (selectedID.size() > 0) {
            boolean isCorrect = true;
            String _ids = "";
            for (int i = 0; i < selectedID.size(); i++) {
                if (i != selectedID.size() - 1) {
                    _ids += selectedID.get(i) + ",";
                } else {
                    _ids += selectedID.get(i);
                }
            }

            ExamQuestion question = mQuestion.get(whichOne);
            for (ExamOption option : question.getDataList()) {
                if (option.getIs_correct() == 0) {
                    if (_ids.contains(option.getId())) {
                        isCorrect = false;
                        break;
                    }
                }
            }


            current = whichOne;
            Singleton.getInstance().updDatiList(whichOne + 1, true);

            Map m = new HashMap();
            m.put("id", question.getId());
            m.put("ans", _ids + "");
            m.put("keys", question.getType());
            singleton.addData(m);

//
//            if(whichOne==mQuestion.size()-1){
//                L.i("结束");
//                ActivitySkipUtil.skipAnotherActivity(ExamActivity.this, MyStSucActivity.class, false);
//
//            }else{
////                gotoNextPage(whichOne);
//            }


//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(_ids);
//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(isCorrect ? 1 : 0);
        } else {
//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(null);
//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(2);
        }
    }


    /**
     * 执行下一个页面
     *
     * @param currentPosition 当前页
     */
    private void gotoNextPage(int currentPosition) {
        int nextPage = currentPosition + 1;
        if (nextPage < mQuestion.size() + 1) {
            mViewPager.setCurrentItem(nextPage, true);
        }
        if (nextPage == mQuestion.size()) {
            mViewPagerAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onJudge(String selectedId, int whichOne) {
        boolean isCorrect = false;
        ExamQuestion question = mQuestion.get(whichOne);

        for (ExamOption option : question.getDataList()) {
            if (option.getIs_correct() == 1) {
                if (option.getId().equals(selectedId)) {
                    isCorrect = true;
                    break;
                }
            }
        }

//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(selectedId);
//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(isCorrect ? 1 : 0);

        gotoNextPage(whichOne);
    }


    private void loadData(String id) {

        L.i("main", Constant.uid + "::::" + Constant.token + "::::" + id);
        singleton.clearDati();
        Ion.with(this)
                .load("http://api.futuyj.com/lesson/test/redo")
                .setBodyParameter("userId", Constant.uid)
                .setBodyParameter("token", Constant.token)
                .setBodyParameter("testId", id)
                .as(new TypeToken<ZhenTiNewModel>() {
                })
                .setCallback(new FutureCallback<ZhenTiNewModel>() {
                    @Override
                    public void onCompleted(Exception e, ZhenTiNewModel result) {
                        // do stuff with the result or error
                        L.i("main", result + "<<<<<00000000000000000<<" + result.getSuccess() + ":::");

                        zhenTiNewModel = result;
                        if (1 == Tools.isIntNull(result.getSuccess())) {
                            for (int i = 0; i < result.getItems().size(); i++) {
                                ZhenTiNewModel.ItemsBean d = result.getItems().get(i);
                                if ("".equals(Tools.isNull(questionID))) {
                                    questionID = d.getQuestion().getId();
                                }
                                ExamQuestion ques = new ExamQuestion();
                                ques.setId(d.getQuestion().getId());
                                ques.setStem(d.getQuestion().getStem());
//                            ques.setType("single_choice".equals(d.getQuestionType())?0:1);
                                ques.setType(Tools.getType(Tools.isNull(d.getQuestionType())));
                                L.i("main", "ools.getType(Tools.isNull(d.getQuestionType()))>>>>" + Tools.getType(Tools.isNull(d.getQuestionType())));

//                                ques.setDifficulty(Tools.isIntNull(d.getQuestion().getDifficulty()));
                                ques.setCourseId(d.getQuestion().getCopyId());
                                ques.setqNo(0);
                                ques.setSource(0);
                                ques.setCollection(Tools.isIntNull(d.getFavorite()));
                                ques.setAnalysis(d.getQuestion().getAnalysis());
                                ZhenTiNewModel.ItemsBean.QuestionBean q = d.getQuestion();
                                int j = 0;
                                List<ExamOption> options = new ArrayList();
                                for (String str : q.getMetas().getChoices()) {
                                    ExamOption opt = new ExamOption();
                                    opt.setId(j + "");
                                    opt.setContent(str);
                                    options.add(opt);
                                    j++;
                                }
                                ques.setDataList(options);


                                Map tmap = new HashMap();
                                tmap.put("index", i + 1);
                                tmap.put("type", ques.getType());
//                            tmap.put("name", Tools.delHTMLTag(q.getStem()));
                                tmap.put("is", false);
                                singleton.addD(tmap);

                                mQuestion.add(ques);
                            }

                            lmname = result.getLmname();
//                            mViewPagerAdapter.notifyDataSetChanged();
                            initView();
                            singleton.setStartTime(Tools.getTime1());
                            singleton.setId(result.getPaperResult().getId());
//                        singleton.setEndTime(ke);
//                        singleton.setKeys(Tools.isNull(keys));


                            L.i("main", "lmname:::" + lmname);

                        } else {
                            Toasty.normal(getApplicationContext(), !"".equals(Tools.isNull(result.getError())) ? result.getError() : (result.getLmname() + "暂无此类型的练习题")).show();
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException ex) {
                                ex.printStackTrace();
                            }
                            finish();
                        }
                    }
                });
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                showpopup();
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private void showpopup() {

        new MaterialDialog.Builder(this)
                .title(R.string.title1)
                .content(R.string.content)
                .positiveText(R.string.agree)
                .positiveColor(Color.BLACK)
                .negativeColor(Color.BLACK)
                .negativeText(R.string.disagree)
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.NEUTRAL) {
                        } else if (which == DialogAction.POSITIVE) {
                            finish();
//                          Toast.makeText(MainActivity.this, "同意" + dataChoose, Toast.LENGTH_LONG).show();
                        } else if (which == DialogAction.NEGATIVE) {
                        }

                    }
                })
                .show();
    }

    private void share() {
        ZhenTiNewModel.ItemsBean.ShareBean shareBean = zhenTiNewModel.getItems().get(current).getShare();
        if (null != shareBean) {
            OnekeyShare oks = new OnekeyShare();
            oks.disableSSOWhenAuthorize();
            oks.setTitle(shareBean.getTitle());
            oks.setTitleUrl(shareBean.getUrl());
            oks.setText(shareBean.getTitle());
            oks.setImageUrl(shareBean.getImage());
            oks.setUrl(shareBean.getUrl());
            oks.setSite(shareBean.getTitle());
            oks.setSiteUrl(shareBean.getUrl());
            oks.show(ExamActivity.this);
        }
    }


}
